const { createOrUpdate, findCarts, updateCarts, removeCarts, selectAllCarts, unSelectAllCarts ,totalCarts} = require('../service/cart.service')
const { cartAddError, cartFormatError } = require("../constant/err.type")

class CartController {
    async add(ctx, next) {
        // 校验商品是否存在 ？？？？
        // 获取参数
        const user_id = ctx.state.user.id
        const { goods_id } = ctx.request.body
        // 操作数据库 
        try {
            const res = await createOrUpdate(user_id, goods_id)
            // 返回客户端
            ctx.body = {
                code: 0,
                message: "添加购物车成功",
                result: res
            }
        } catch (err) {
            console.error(err)
            ctx.app.emit('error', cartAddError, ctx)
        }
    }
    async findAll(ctx, next) {
        // 解析pageSize pageNum
        const { pageNum = 1, pageSize = 10 } = ctx.request.query
        // 调用数据处理相关方法
        const res = await findCarts(pageNum, pageSize)
        // 返回数据结果
        ctx.body = {
            code: 0,
            message: "获取购物车列表成功",
            result: res
        }
    }
    async update(ctx, next) {
        const id = ctx.request.params.id
        const { number, selected } = ctx.request.body
        // 解析参数
        if (number === undefined && selected === undefined) {
            cartFormatError.message = "number和selected不能同时为空"
            return ctx.app.emit('error', cartFormatError, ctx)
        }
        // 操作数据库
        const res = await updateCarts({ id, number, selected })
        // 返回结果
        ctx.body = {
            code: 0,
            message: "更新购物车成功",
            result: res
        }
    }
    // 删除对象
    async remove(ctx, next) {
        const { ids } = ctx.request.body
        const res = await removeCarts(ids)
        ctx.body = {
            code: 0,
            message: '删除购物车成功',
            result: res
        }
    }
    // 全选
    async selectAll(ctx, next) {
        const user_id = ctx.state.user.id
        const res = await selectAllCarts(user_id)
        ctx.body = {
            code: 0,
            message: '全部不选中',
            result: res
        }
    }
    // 全不选
    async unSelectAll(ctx, next) {
        const user_id = ctx.state.user.id
        const res = await unSelectAllCarts(user_id)
        ctx.body = {
            code: 0,
            message: '取消全部选中成功',
            result: res
        }
    }
    // 总数
    async total(ctx, next) {
        const user_id = ctx.state.user.id
        const res = await totalCarts(user_id)
        ctx.body = {
            code: 0,
            message: '获取总数成功',
            result: res
        }
    }
}
module.exports = new CartController()